import { Injectable } from '@angular/core';
import * as wellknown from 'wellknown';
import * as  turf from '@turf/turf';
import { StyleService } from './style.service';
import { MapService } from './map.service';

export const funMarkTpl = (url) => {
  return ` <object data="${url}"
type="image/svg+xml"
codebase="http://www.adobe.com/svg/viewer/install/" />`;
};

export const funMarkTpl2 = (url,) => {
  return ` <object data="${url}"
type="image/svg+xml"
codebase="http://www.adobe.com/svg/viewer/install/" />`;
};
@Injectable({
  providedIn: 'root'
})
export class LayerManageService {
  markerList = [];
  constructor(
    private styleService: StyleService,
    private mapService: MapService
  ) { }
  /**
   * 
   * @param map 地图实例对象
   * @param e 数据
   */
  fitPositionAddLayer(map, e, styleFlag, beforeId = '', pointISopen, zoomlevel=15) {
    const { geo } = e;
    const geojson = wellknown.parse(geo);
    const { type } = geojson;
    let zoomCenter: any = [];
    switch (type) {
      case 'Point':
        const eventDiffusionStyle = this.styleService.getStyleByflag('animated_point', geojson);
        this.mapService.addSymbolDiffusionLayer(eventDiffusionStyle, {
          size: 100,         // 扩散符合大小
          fcolor: '#d92c2c', // 填充颜色
          fopacity: 0.5,     // 填充初始透明度
          scolor: '#d92c2c', // 描边颜色
          sopacity: 1,       // 描边透明度
          lineWidth: 3,      // 描边宽度,
          duration: 1500     // 持续时间
        });
        zoomCenter = turf.center(geojson).geometry.coordinates;
        if (pointISopen) {
          const pagePointStyle = this.styleService.getStyleByflag(`${styleFlag}_point`, geojson);
          this.mapService.addGeoJSONLayer(pagePointStyle, {});
          zoomCenter = turf.center(geojson).geometry.coordinates;
        }

        map.flyTo({
          center: zoomCenter,
          zoom: zoomlevel,
        });
        break;
      case 'MultiLineString':
        const pageLinetyle = this.styleService.getStyleByflag(`${styleFlag}_line`, geojson);
        this.mapService.addGeoJSONLayer(pageLinetyle, { "beforeId": beforeId }); // 确定好前者到底是哪个图层！
        const coordinate = geojson.coordinates[0];
        // console.log(coordinate);
        this.styleService.fitLineBounds(map, coordinate);
        break;
      case 'MultiPolygon':
        zoomCenter = turf.center(geojson).geometry.coordinates;
        break;
      default:
        break;
    }
  }
  /**
   * @param shape  空间数据
   * @param style  获取样式的style标识
   * @param beforId  加载哪个图层前面
   * @param isFormateGeo  是否要转换成geojson   true 是
   */
  addUniLayer(shape, style, beforId, isFormateGeo = true) {
    let geojson;
    if (isFormateGeo) {
      geojson = wellknown.parse(shape);
    } else {
      geojson = shape;
    }
    const Style = this.styleService.getStyleByflag(style, geojson);
    this.mapService.addGeoJSONLayer(Style, { beforeId: beforId });
  }
  /**
   * 清楚图层
   */
  removeLayer() {
    const layers = this.styleService.getLayersIDlist();
    this.mapService.removeLayerByIds(layers);
  }
  drawDynamitcLine(layerID, feature, color) {
    const defaultLinetyle = {
      type: 'line',
      id: layerID,
      source: {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: feature
        }
      },
      layout: {
        'line-join': 'round',
        'line-cap': 'round'
      },
      paint: {
        'line-color': color,
        'line-width': [
          'match',
          ['to-number', ['get', 'jb']],
          1, 4,
          2, 3,
          3, 2,
          4, 1,
          1
        ],
        'line-dasharray': [1, 4, 2]
      }
    };
    this.mapService.addGeoJSONLayer(defaultLinetyle, {});
  }
  // todo让线运动
  animateParkingOutline(mapboxglmap, dashArraySeq, dynamicLayerId) {
    let step = 0;
    let raf;
    step = (step + 1) % dashArraySeq.length;
    if (mapboxglmap.getLayer(dynamicLayerId)) {
      mapboxglmap.setPaintProperty(
        dynamicLayerId,
        'line-dasharray',
        dashArraySeq[step],
        {}
      );
    }
    clearTimeout(raf);
    raf = setTimeout(() => {
      this.animateParkingOutline(mapboxglmap, dashArraySeq, dynamicLayerId);
    }, 60);
  }
  /**
   * 判断指定id的图层是否开启
   * @param map  地图实例
   * @param id  图层id
   * 存在返回true ， 不存在返回false
   */
  isOpenLayer(map, id) {
    if (map && map.getLayer(id)) {
      return true;
    } else {
      return false;
    }
  }
  /**
   * 以下添加marker的相关方法
   * @param map 
   * @param data 
   * @param glayerid 
   * @param options 
   */
  addMarkLayer(map, data, glayerid, options) {
    this.markerList[glayerid] = [];
    data.forEach(point => {
      const marker = this.createMaker(map, point, options);

      this.markerList[glayerid].push(marker);
    });
  }
  removeMarkLayerByGid(gid) {
    if (this.markerList[gid] && this.markerList[gid].length > 0) {
      this.markerList[gid].forEach(marker => {
        marker.remove();
      });
      this.markerList[gid] = [];
    }
  }
  createMaker(map, data, options) {
    const tpl = funMarkTpl(options.img);
    const el = this.createElementFromHTML(tpl);
    const marker = new mapboxgl.Marker(el)
      .setLngLat(data.coordinates)
      .addTo(map);
    return marker;
  }
  createElementFromHTML(htmlString) {
    const div = document.createElement('div');
    div.innerHTML = htmlString.trim();
    return div.firstChild;
  }
}
